/*
 * @Descripttion:
 * @version:
 * @Author: lfzxs@qq.com
 * @Date: 2023-08-25 13:49:44
 * @LastEditors: lfzxs@qq.com
 * @LastEditTime: 2023-09-19 11:33:25
 */
package object

import (
	"database/sql"
	"fmt"
	"time"

	"gitee.com/g_boot/attachment/utils"
	"github.com/go-logr/logr"
)

type FileInfo struct{
	File_code string
	File_hash string
	File_name string
	File_ext string
	File_path string
	File_size int64
	File_link string
	Real_file string
}

type MySql_operator struct{
	logger logr.Logger
	Db *sql.DB
	//表名前缀
	Prefix string
}

func NewMySqlOperator(user string,pwd string,ip string,port string,database string,logger logr.Logger)*MySql_operator{
	dbconstr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?loc=Local", user,pwd,ip,port,database)
	db, err := sql.Open("mysql", dbconstr)
	if err != nil {
		panic(err.Error())
	}
	
	operator := &MySql_operator{
		logger: logger,
		Db: db,
	}
	return operator

}

func (obj *MySql_operator) CreateTabels(){

}

func (obj *MySql_operator) GetTabName()string{
	if(len(obj.Prefix) == 0){
		return "attachment_file"
	}else{
		return obj.Prefix + "_attachment_file"
	}
}


func (obj *MySql_operator) GetFileKeyFormHash(hash string)(fileKey string,err error){
	tablename := obj.GetTabName() 

    sql := fmt.Sprintf("select file_code from %s where file_hash=%s",tablename,hash)

	obj.logger.Info(sql, "timestamp", time.Now())

	rows, err := obj.Db.Query(sql)
	if err != nil {
		panic(err.Error())
	}
	defer rows.Close()

	return
}


func (obj *MySql_operator) SaveFileInfo(data *FileInfo)(fileKey string,err error){
	tablename := obj.GetTabName() 

	data.File_code = utils.CreateSnowflakeIDStr()

    sql := fmt.Sprintf("insert into %s (record_id,created_at,file_code,file_hash,file_type,file_name,file_ext,file_path,file_size,file_link)"+
										 "values(?,NOW(),?,?,0,?,?,?,?,?)",tablename)

	obj.logger.Info(sql)

	// 执行插入操作
    _, err = obj.Db.Exec(sql, data.File_code,data.File_code,data.File_hash,data.File_name, data.File_ext,data.File_path,data.File_size,data.File_link)

    // 返回错误信息
    if err != nil {
        return "",err
    }

    return data.File_code,nil

	
}